package com.shihan.rabbitmq.advancedfeatures.listener;

import com.rabbitmq.client.Channel;
import com.shihan.rabbitmq.advancedfeatures.config.RabbitMQConfig;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description Spring Boot 方式的消息异步监听回调的方法
 * @Author shihan
 * @Date 2021/1/3 10:56
 * @Version 1.0
 */
@Component
public class MyMessageListener {

    /**
     * 具体参数，可以通过 @RabbitListener 注解中的描述来动态添加
     * @param channel
     * @param message
     * @param msgStr
     * @param deliveryTag
     */
    @RabbitListener(queues = {RabbitMQConfig.QUEUE_NAME},ackMode = "MANUAL")
    public void handelMessage(
            Channel channel,
            Message message,
            @Payload String msgStr,
            @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag ) {

        // 消息的内容
        System.out.println("【消息的内容是】：" + msgStr);

        // 手动确认
        try {

            // 消费成功
            // channel.basicAck(deliveryTag,false);

            // 拒绝消息 TODO 好像在 yml 中配置的重试时间间隔、最大重试次数，都没有效果！
            channel.basicReject(deliveryTag,true);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
